package com.szholly.plug.safe.security;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

import com.szholly.plug.safe.login.LoginLock;

/**
 * 定义spring security的自定义评证提供器
 */
public class CustomAuthenticationProvider extends
		AbstractUserDetailsAuthenticationProvider {

	private MyUserDetailService userDetailsService;

	public MyUserDetailService getUserDetailsService() {
		return userDetailsService;
	}

	public void setUserDetailsService(MyUserDetailService service) {
		userDetailsService = service;
	}

	protected void additionalAuthenticationChecks(UserDetails userDetails,
			UsernamePasswordAuthenticationToken authentication)
			throws AuthenticationException {

		if (authentication.getCredentials() == null) {
			throw new AuthenticationServiceException("用户名或密码错误！");
		}

		String presentedPassword = authentication.getCredentials().toString();
		if (!userDetails.getPassword().equals(presentedPassword)) {
			// 在这里记录用户登录失败一次，记录帐号+登录时间
			LoginLock.setLogin(authentication.getName());
			throw new AuthenticationServiceException("用户名或密码错误！");
		}
	}

	protected final UserDetails retrieveUser(String username,
			UsernamePasswordAuthenticationToken authentication)
			throws AuthenticationException {
		UserDetails loadedUser;
		this.getUserDetailsService().setOrgid(((UsernamePasswordAuthenticationTokenExt)authentication).getOrgid());
		loadedUser = this.getUserDetailsService().loadUserByUsername(username);
		if (loadedUser == null) {
			throw new AuthenticationServiceException("用户名或密码错误！");
		}
		return loadedUser;
	}
}